package com.hxy.modules.common.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

@Component
public class UploadFileUtil {

    private static  String uploadPath;

    private static  String photoRealPath;


    @Value("${photo.save.path}")
    public void setUploadPath(String path) {
        uploadPath = path;
    }

    @Value("${photo.save.realpath}")
    public void setPhotoRealPath(String realpath) {
        photoRealPath = realpath;
    }


    /**
     * 图片上传
     * @param req
     * @param multiReq
     * @return
     */
    public static String UploadFile(HttpServletRequest req, MultipartHttpServletRequest multiReq) {
        // 获取上传文件的路径
        String uploadFilePath = multiReq.getFile("file").getOriginalFilename();
        // 截取上传文件的文件名
        //String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));
        // 截取上传文件的后缀
        String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
        OutputStream fos = null;
        InputStream fis = null;
        String FileName = ("" + UUID.randomUUID()).replace("-","");
        try {
            fis =  multiReq.getFile("file").getInputStream();
            fos = new FileOutputStream(new File( photoRealPath + FileName + ".") + uploadFileSuffix);

            byte[] temp = new byte[1024];
            int i = fis.read(temp);
            while (i != -1){
                fos.write(temp,0,temp.length);
                fos.flush();
                i = fis.read(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("文件上传失败");
        } finally {
            close(fos,fis);
        }
        return uploadPath + FileName + "." +uploadFileSuffix;
    }


    private static void close(OutputStream fos,InputStream fis){
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
